package utils;

import book.Book;
import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;
import constant.Constant;

public class AnalyzingBorrowedBook {

    /**
     * 存到文件当中
     * @param pairOfUidAndBookIds
     * @param filename
     */
    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds,
                            String filename) {

        int booksUseLen = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i] != null) {
                booksUseLen++;
            }
        }

        StringBuilder jsonArray = new StringBuilder();

        for (int i = 0; i < booksUseLen; i++) {
            if(pairOfUidAndBookIds[i] != null) {
                jsonArray.append(pairOfUidAndBookIds[i].toJson());
                if (i != booksUseLen-1) {
                    jsonArray.append("\n");
                }
            }
        }

        FileUtils.writeFile(jsonArray.toString(),filename);/* */

    }


    public PairOfUidAndBookId[] loadObject(String filename)  {

        String content = FileUtils.readFile(filename);

        if (content == null || content.isEmpty()) {
            System.out.println("File is empty or does not exist: " + filename);
            return null;
        }
        //2. 使用\n作为分隔符进行字符串分割
        String[] bookJsonStrings = content.split("\n");

        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[bookJsonStrings.length];

        for (int i = 0; i < bookJsonStrings.length; i++) {

            PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId();

            String[] uidAndBookIds = bookJsonStrings[i].split(",");

            pairOfUidAndBookId.setUserId(Integer.parseInt(uidAndBookIds[0]));

            pairOfUidAndBookId.setBookId(Integer.parseInt(uidAndBookIds[1]));

            pairOfUidAndBookIds[i] = pairOfUidAndBookId;
        }

        return pairOfUidAndBookIds;
    }


    public static void main(String[] args) {
        AnalyzingBorrowedBook analyzingBorrowedBook = new AnalyzingBorrowedBook();
        PairOfUidAndBookId[] ret = analyzingBorrowedBook.loadObject(Constant.BORROWED_BOOK_FILE_NAME);
        for (int i = 0; i < ret.length; i++) {
            System.out.println(ret[i]);
        }
    }

    public static void main1(String[] args) {

        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[2];
        pairOfUidAndBookIds[0] = new PairOfUidAndBookId(1,1001);
        pairOfUidAndBookIds[1] = new PairOfUidAndBookId(2,2001);


        AnalyzingBorrowedBook analyzingBorrowedBook = new AnalyzingBorrowedBook();
        analyzingBorrowedBook.storeObject(pairOfUidAndBookIds, Constant.BORROWED_BOOK_FILE_NAME);
    }



}
